<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>promise实现循环打印红黄绿</title>
</head>

<body>
    <script>
        function red() {
            console.log("red");
        }
        function yellow() {
            console.log("yellow");
        }
        function green() {
            console.log("green");
        }

        function task(time, light) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    if (light == 'red') {
                        red();
                    } else if (light == 'yellow') {
                        yellow();
                    } else if (light == 'green') {
                        green();
                    }
                    resolve();
                }, time)
            })
        }

        // 采用promise链式方式
        function runTask() {
            task(1000, 'red').then(() => task(1000, 'yellow')).then(() => task(1000, 'green')).then(runTask)
        }

        // 采用asyns/await方式
        // async function runTask() {
        //     await task(1000, 'red');
        //     await task(1000, 'yellow');
        //     await task(1000, 'green');
        //     runTask();
        // }

        runTask();

    </script>
</body>

</html>